package com.sixth.sso.service;

import com.sixth.core.entity.Menu;
import com.sixth.core.entity.Patient;
import com.sixth.core.entity.User;
import com.sixth.core.vo.R;
import com.sixth.sso.feign.MenuFeign;
import com.sixth.sso.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MenuFeign menuFeign;

    @Autowired
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取请求头中的source-client
        String sourceClient = request.getHeader("source-client");

        // 根据source-client的不同做出不同的处理
        if ("miniapp".equalsIgnoreCase(sourceClient)) {
            return handleMiniAppLogin(username);
        } else {
            return handleDefaultLogin(username);
        }
    }

    private UserDetails handleMiniAppLogin(String username) {
        // 针对小程序的登录逻辑处理
        R<Patient> r = userFeign.getByNamePatient(username);
        if (r.getCode() == 200) {
            Patient patient = r.getData();
            // 直接返回不带权限的 UserDetails 对象
            return new org.springframework.security.core.userdetails.User(
                    username,
                    patient.getPassword(),
                    new ArrayList<>()
            );
        }
        throw new UsernameNotFoundException("User not found");
    }


    private UserDetails handleDefaultLogin(String username) {
        // 默认的登录逻辑处理
        R<User> r = userFeign.getByName(username);
        if (r.getCode() == 200) {
            User user = r.getData();
            R<List<Menu>> r1 = menuFeign.getByUserId(user.getUserId());
            List<Menu> menuList = r1.getData();

            // 过滤掉空或无效的权限
            Collection<SimpleGrantedAuthority> authorities = menuList.stream()
                    .map(Menu::getPercode)
                    .filter(percode -> percode != null && !percode.trim().isEmpty())
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());

            return new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);
        }
        throw new UsernameNotFoundException("User not found");
    }

}
